//
//  NewsCollectionView.m
//  News
//
//  Created by Han on 15-4-15.
//  Copyright (c) 2015年 IPingLun. All rights reserved.
//

#import "NewsCollectionView.h"

#define CELL_IDENTIFIER @"WaterfallCell"
#define HEADER_IDENTIFIER @"WaterfallHeader"
#define FOOTER_IDENTIFIER @"WaterfallFooter"

@implementation NewsCollectionView {

    CHTCollectionViewWaterfallLayout *mWaterfalllayout;
    UIRefreshControl *mRefreshControl;
    NewsPresenter *mPresenter;
    NSMutableArray *mData;
    int mPager;
    BOOL mFristLoad;
    
}

@synthesize newsViewDelegate, channelId;

- (id) initWithFrame:(CGRect)frame
{
    mWaterfalllayout = [[CHTCollectionViewWaterfallLayout alloc] init];
    
    mWaterfalllayout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    mWaterfalllayout.headerHeight = 0;
    mWaterfalllayout.footerHeight = 0;
    mWaterfalllayout.minimumColumnSpacing = 10;
    mWaterfalllayout.minimumInteritemSpacing = 10;
    mWaterfalllayout.columnCount = 2;
    
    self = [super initWithFrame:frame collectionViewLayout:mWaterfalllayout];
    
    if (self) {
        
        [self drawView];
        
        mData = NSMutableArray.new;
        mPager = 1;
        mFristLoad = true;
        
        mPresenter = NewsPresenter.new;
        mPresenter.delegate = self;
        
        
    }
    
    return self;
}


- (void) fristLoadData {
    
    if (!mFristLoad) {
        return;
    }
    

    [self setRefreshOffset];
    [self refresh];
}

- (void) setRefreshOffset {

    // 先执行划到表格顶部的动画
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.25];
    self.contentOffset = CGPointZero;
    [UIView commitAnimations];
    
    
    // 再执行下拉动画
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.25];
    self.contentOffset = CGPointMake(0.0, -mRefreshControl.frame.size.height); // 注意位移点的y值为负值
    [UIView commitAnimations];

}


- (void)refresh {
    
    mPager = 1;
    
    // 第一次进入
    if (!mRefreshControl.refreshing) {
        //NSLog(@"beginRefreshing");
        [mRefreshControl beginRefreshing];
    }
    
    [self performSelector:@selector(loadData) withObject:nil afterDelay:0.5f];
    
}

- (void)loadData {
    [mPresenter getNewsList:mPager];
    
}


- (void) onLoadNewsListStart {
    
}

- (void) onLoadNewsListSuccess:(NewsListModel *)newsList {
    
    if (mPager == 1) {
        [mData removeAllObjects];
        mWaterfalllayout.footerHeight = 40;
    }
    
    [mData addObjectsFromArray: newsList.dataList];
    
    
    mPager++;
    
    [self reloadData];
    
}

- (void) onLoadNewsListFinish {
    
    if (mFristLoad)
        mFristLoad = false;

    
    [mRefreshControl endRefreshing];
}

- (void) onLoadNewsListFailure {
    
}





//UICollectionView 被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    News *news = [mData objectAtIndex:indexPath.row];
    
    [newsViewDelegate jumpToDetail:news.news_id];
    //NSLog(@"indexPath.row=%d", indexPath.row);
    
}




- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableView = nil;
    
    if ([kind isEqualToString:CHTCollectionElementKindSectionHeader]) {
        /*
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                          withReuseIdentifier:HEADER_IDENTIFIER
                                                                 forIndexPath:indexPath];
        */
     
    } else if ([kind isEqualToString:CHTCollectionElementKindSectionFooter]) {
        
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                         withReuseIdentifier:FOOTER_IDENTIFIER
                                                                forIndexPath:indexPath];
        
    }
    
    return reusableView;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return mData.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WaterfallCell *cell =
    (WaterfallCell *)[collectionView dequeueReusableCellWithReuseIdentifier:CELL_IDENTIFIER forIndexPath:indexPath];
    
    cell.news = [mData objectAtIndex:(NSUInteger)indexPath.row];
    
    return cell;
}



#pragma mark - CHTCollectionViewDelegateWaterfallLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    News *news = [mData objectAtIndex:(NSUInteger)indexPath.row];
    
    float height = [WaterfallCell getHeight:news.title :news.comment1 :news.comment2 :news.comment3];
    
    return CGSizeMake(WATERFALL_WIDTH, height);
    
    
    /*
    return [self fd_heightForCellWithIdentifier:@"CELL_IDENTIFIER" configuration:^(WaterfallCell *cell) {
        cell.entity = self.feedEntities[indexPath.row];
    }];
     */
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    
    // 下拉到最底部时显示更多数据
    if(scrollView.contentOffset.y >= ((scrollView.contentSize.height - scrollView.frame.size.height))) {
        
        //NSLog(@"下拉到最底部时显示更多数据");
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NoMoreDataEvent" object:self userInfo:nil];
        [self loadData];
    }
    
}


- (void)drawView {
    
    self.backgroundColor = [UIColor clearColor];
    
    self.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.dataSource = self;
    self.delegate = self;
    
    [self registerClass:[WaterfallCell class] forCellWithReuseIdentifier:CELL_IDENTIFIER];
    //[self registerClass:[WaterfallHeader class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:HEADER_IDENTIFIER];
    

    
    [self registerClass:[WaterfallFooter class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionFooter  withReuseIdentifier:FOOTER_IDENTIFIER];
    
    
    mRefreshControl = [[UIRefreshControl alloc] init];
    mRefreshControl.tintColor = [UIColor grayColor];
    [mRefreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
    
    [self addSubview:mRefreshControl];
    
    self.alwaysBounceVertical = YES;  //解决第一次加载失败无数据UIRefreshControl不启作用
}


@end
